﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Web.Configuration;
using System.Configuration;
using System.Text;

/// <summary>
/// Summary description for WebConfig
/// </summary>
public class WebConfig
{

    public const string DEFAULT_DATABASE_CONN_STR_NAME = "MERCATOR_histConnectionString";//"MercatorNSConnectionString";
    public const string DEFAULT_SECURITY_CONN_STR_NAME = "SecurityConnectionString";

    public WebConfig()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static System.Web.UI.WebControls.ListItem[] GetDatabaseList()
    {
        System.Web.UI.WebControls.ListItem[] retListItem=null;

        try
        {
            // Obtem uma lista de pares de chave e valor
            // onde a chave é o texto da DropDownList 
            // e o valor é a string de conexao ao banco de dados
            Dictionary<string, string> listDatabase;
            listDatabase = GetDatabaseListDic();
            
            // cria array de ListItem com o tamanho necessario
            retListItem=new System.Web.UI.WebControls.ListItem[listDatabase.Count];

            int itemCount = 0;
            foreach (KeyValuePair<string,string> kvpItem in listDatabase)
            {

                System.Web.UI.WebControls.ListItem listItem = new System.Web.UI.WebControls.ListItem();
                listItem.Text = kvpItem.Key.Substring(1,kvpItem.Key.Length-1);
                listItem.Value = kvpItem.Value;
                retListItem[itemCount++] = listItem;
                
            }
        }
        catch (Exception)
        {

            //throw;
        }

        return retListItem;
    }

    public static System.Web.UI.WebControls.ListItem[] GetDatabaseList(string FilterString)
    {
        System.Web.UI.WebControls.ListItem[] retListItem = null;

        try
        {
            // Obtem uma lista de pares de chave e valor
            // onde a chave é o texto da DropDownList 
            // e o valor é a string de conexao ao banco de dados
            Dictionary<string, string> listDatabase;
            listDatabase = GetDatabaseListDic(FilterString);

            // cria array de ListItem com o tamanho necessario
            retListItem = new System.Web.UI.WebControls.ListItem[listDatabase.Count];

            int itemCount = 0;
            foreach (KeyValuePair<string, string> kvpItem in listDatabase)
            {

                System.Web.UI.WebControls.ListItem listItem = new System.Web.UI.WebControls.ListItem();
                listItem.Text = kvpItem.Key.Substring(1, kvpItem.Key.Length - 1);
                listItem.Value = kvpItem.Value;
                retListItem[itemCount++] = listItem;

            }
        }
        catch (Exception)
        {

            //throw;
        }

        return retListItem;
    }

    private static Dictionary<string, string> GetDatabaseListDic()
    {
        Dictionary<string, string> databaseListDic = 
            new Dictionary<string,string>();

        try
        {
            // Get the connectionStrings key,value pairs collection.
            ConnectionStringSettingsCollection connectionStrings =
                WebConfigurationManager.ConnectionStrings
                as ConnectionStringSettingsCollection;

            // Get the collection enumerator.
            System.Collections.IEnumerator connectionStringsEnum =
                connectionStrings.GetEnumerator();

            // Loop through the collection and 
            // display the connectionStrings key, value pairs.
            int i = 0;
            while (connectionStringsEnum.MoveNext())
            {
                string name = connectionStrings[i].Name;
                i += 1;

                // Exibe somente nomes de conexoes comecando com #
                if (name.Substring(0, 1) != "#") continue;
                
                databaseListDic.Add(name, connectionStrings[name].ConnectionString);

            }       
        }
        catch (Exception)
        {

            //throw;
        }

        return databaseListDic;
    }

    private static Dictionary<string, string> GetDatabaseListDic(string FilterString)
    {
        Dictionary<string, string> databaseListDic =
            new Dictionary<string, string>();

        try
        {
            // Get the connectionStrings key,value pairs collection.
            ConnectionStringSettingsCollection connectionStrings =
                WebConfigurationManager.ConnectionStrings
                as ConnectionStringSettingsCollection;

            // Get the collection enumerator.
            System.Collections.IEnumerator connectionStringsEnum =
                connectionStrings.GetEnumerator();

            // Loop through the collection and 
            // display the connectionStrings key, value pairs.
            int i = 0;
            while (connectionStringsEnum.MoveNext())
            {
                string name = connectionStrings[i].Name;
                i += 1;

                // Exibe somente nomes de conexoes comecando com #
                //if (name.Substring(0, 1) != "#") continue;
                if (!name.StartsWith(FilterString)) continue;

                databaseListDic.Add(name, connectionStrings[name].ConnectionString);

            }
        }
        catch (Exception)
        {

            //throw;
        }

        return databaseListDic;
    }

    private static Dictionary<string, string> GetDatabaseListDictest()
    {
        Dictionary<string, string> databaseListDic=null;

        try
        {
            // Set the root path of the Web application that contains the
            // Web.config file that you want to access.
            string configPath = "/";// "/MyAppRoot";

            // Get the configuration object to access the related Web.config file.
            Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);

            //System.Web.Configuration.con

            // Get the object related to the <identity> section.
            IdentitySection section =
              (IdentitySection)config.GetSection("system.web/identity");

            // Read the <identity> section.
            StringBuilder identity = new StringBuilder();
            identity.Append("Impersonate: ");
            identity.Append(section.Impersonate.ToString());

            // Display the <identity> information.
            //ConfigId = identity.ToString();            
        }
        catch (Exception)
        {

            //throw;
        }

        return databaseListDic;
    }

    // Show the use of ConnectionStrings. 
    // If called from within a client application,
    // the GetWebApplicationSection(string) gets the default section 
    // from the machine.config.
    // If called from within a Web aplication it gets the
    // section from the configuration file located at the 
    // application current level. 
    static void GetConnectionStrings()
    {

        // Get the connectionStrings key,value pairs collection.
        ConnectionStringSettingsCollection connectionStrings =
            WebConfigurationManager.ConnectionStrings
            as ConnectionStringSettingsCollection;

        // Get the collection enumerator.
        System.Collections.IEnumerator connectionStringsEnum =
            connectionStrings.GetEnumerator();

        // Loop through the collection and 
        // display the connectionStrings key, value pairs.
        int i = 0;
        Console.WriteLine("[Display connectionStrings]");
        while (connectionStringsEnum.MoveNext())
        {
            string name = connectionStrings[i].Name;
            Console.WriteLine("Name: {0} Value: {1}",
            name, connectionStrings[name]);
            i += 1;
        }

        Console.WriteLine();
    }
    
    public string LeConfig()
    {
        string ConfigId = "";
        try
        {
            // Set the root path of the Web application that contains the
            // Web.config file that you want to access.
            string configPath = "/";// "/MyAppRoot";

            // Get the configuration object to access the related Web.config file.
            Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);

            // Get the object related to the <identity> section.
            IdentitySection section =
              (IdentitySection)config.GetSection("system.web/identity");

            // Read the <identity> section.
            StringBuilder identity = new StringBuilder();
            identity.Append("Impersonate: ");
            identity.Append(section.Impersonate.ToString());

            // Display the <identity> information.
            ConfigId = identity.ToString();

            return ConfigId;
        }
        catch (Exception e)
        {
            ConfigId = e.ToString();
            return "";
        }
    }

    // TODO: create a separate method for MERCATOR database and for security database
    /// <summary>
    /// 
    /// </summary>
    /// <param name="ConnectionStringName"></param>
    /// <param name="SecurityConnstring"></param>
    public static void SetDefaultDatabase(string ConnectionStringName, bool IsSecurityDB)
    {
        try
        {
            // Get the connectionStrings key,value pairs collection.
            ConnectionStringSettingsCollection connectionStrings =
                WebConfigurationManager.ConnectionStrings
                as ConnectionStringSettingsCollection;

            // Get the new selected connection string to the MERCATOR database
            string newConnStr = connectionStrings[ConnectionStringName].ConnectionString;

            // Open current application Web.Config file for update
            Configuration configuration =
              WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath);
            ConnectionStringsSection connStringSection =
              (ConnectionStringsSection)configuration.GetSection("connectionStrings");

            if (connStringSection != null)
            {
                if (IsSecurityDB)
                {
                    // Change default database connection string
                    connStringSection.ConnectionStrings[DEFAULT_SECURITY_CONN_STR_NAME].ConnectionString = newConnStr; 
                }
                else
                {
                    // Change default database connection string
                    connStringSection.ConnectionStrings[DEFAULT_DATABASE_CONN_STR_NAME].ConnectionString = newConnStr; 
                }

                configuration.Save();
            }

        }
        catch (Exception)
        {

            //throw;
        }
    }

    // TODO: create a separate method for MERCATOR database and for security database
    /// <summary>
    /// 
    /// </summary>
    /// <param name="ConnectionStringName"></param>
    /// <param name="SecurityConnstring"></param>
    public static void SetDefaultSecurityDB(string SecurityConnstring)
    {
        try
        {
            // Get the connectionStrings key,value pairs collection.
            ConnectionStringSettingsCollection connectionStrings =
                WebConfigurationManager.ConnectionStrings
                as ConnectionStringSettingsCollection;

            // Get the new selected connection string to the MERCATOR database
            string newConnStrSecurity = connectionStrings[SecurityConnstring].ConnectionString;

            // Open current application Web.Config file for update
            Configuration configuration =
              WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath);
            ConnectionStringsSection connStringSection =
              (ConnectionStringsSection)configuration.GetSection("connectionStrings");

            if (connStringSection != null)
            {

                // Change default security connection string
                connStringSection.ConnectionStrings[DEFAULT_SECURITY_CONN_STR_NAME].ConnectionString = newConnStrSecurity;

                configuration.Save();
            }

        }
        catch (Exception)
        {

            //throw;
        }
    }

    /// <summary>
    /// Create a connectionn string element and add it to
    /// the connection strings section.
    /// </summary>
    static void SampleCreateConnectionStrings()
    {
        // Get the application configuration file.
        System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

        // Get the current connection strings count.
        int connStrCnt = 
            ConfigurationManager.ConnectionStrings.Count;

        // Create the connection string name. 
        string csName = 
            "ConnStr" + connStrCnt.ToString();

        // Create a connection string element and
        // save it to the configuration file.

        // Create a connection string element.
        ConnectionStringSettings csSettings =
                new ConnectionStringSettings(csName,
                "LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;" +
                "Initial Catalog=aspnetdb", "System.Data.SqlClient");

        // Get the connection strings section.
        ConnectionStringsSection csSection =
            config.ConnectionStrings;

        // Add the new element.
        csSection.ConnectionStrings.Add(csSettings);

        // Save the configuration file.
        config.Save(ConfigurationSaveMode.Modified);

    }

    public void Update(string key, string value) 
    {
        Configuration configuration =
          WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath);//Request.ApplicationPath); 
    AppSettingsSection appSettingsSection = 
      (AppSettingsSection)configuration.GetSection("appSettings"); 
       if (appSettingsSection != null) 
       {
           appSettingsSection.Settings[key].Value = value;
           configuration.Save();
       }
    }
    
    /// <summary>
    /// The following method can be used to delete a specific key in the web.config file.
    /// </summary>
    /// <param name="key"></param>
    public void Delete(string key) 
    {
    Configuration configuration =
      WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath); 
    AppSettingsSection appSettingsSection = 
      (AppSettingsSection)configuration.GetSection("appSettings"); 
      if (appSettingsSection != null) 
      { 
         appSettingsSection.Settings.Remove(key);
         configuration.Save();
      } 
    }

    /// <summary>
    /// Obtem string de conexao padrão ao banco de dados da aplicação
    /// </summary>
    /// <returns></returns>
    public static string GetDBConn(string connectionStringName)
    {
        string retDBCon = "";

        try
        {
            if ((connectionStringName == null) || (connectionStringName.Trim() == ""))
                connectionStringName = DEFAULT_DATABASE_CONN_STR_NAME;

            // Get the connectionStrings key,value pairs collection.
            ConnectionStringSettingsCollection connectionStrings =
                WebConfigurationManager.ConnectionStrings
                as ConnectionStringSettingsCollection;
            retDBCon = connectionStrings[DEFAULT_DATABASE_CONN_STR_NAME].ConnectionString;
        }
        catch (Exception)
        {

            //throw;
        }

        return retDBCon;
    }

    /// <summary>
    /// Obtem string de conexao padrão ao banco de dados da aplicação
    /// </summary>
    /// <returns></returns>
    public static string GetDBConn()
    {
        string retDBCon = "";

        try
        {
            retDBCon = GetDBConn(null);
        }
        catch (Exception)
        {

            //throw;
        }

        return retDBCon;
    }

}
